package org.gruposp2p.proyectokarma.gwt.client.cometd;

import org.cometd4gwt.client.CometConnectionListener;
import org.cometd4gwt.client.CometdClient;
import org.cometd4gwt.client.CometdClientImpl;
import org.cometd4gwt.client.CometdJso;
import org.cometd4gwt.client.ConnectionConfig;
import org.cometd4gwt.client.JsoListener;
import org.cometd4gwt.client.ScriptLoadListener;
import org.cometd4gwt.client.Subscription;
import org.gruposp2p.proyectokarma.gwt.client.domain.CometdMetaMessage;
import org.gruposp2p.proyectokarma.gwt.client.json.JSONToDomain;
import org.gruposp2p.proyectokarma.gwt.client.util.ServerPaths;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.allen_sauer.gwt.log.client.Log;
import org.cometd4gwt.client.PersistentSubscribersCometdClient;
import org.gruposp2p.proyectokarma.gwt.client.cometd.ui.ChannelsDialog;
import org.gruposp2p.proyectokarma.gwt.client.ui.UploadDocumentDialog;

public class CometdPanel extends Composite {
	
    private static CometdPanelUiBinder uiBinder = 
    	GWT.create(CometdPanelUiBinder.class);

    interface CometdPanelUiBinder extends UiBinder<Widget, CometdPanel> { }

    @UiField Button publishMessageToChannelHello;
    @UiField Button unsubscribe;
    @UiField Button disconnect;
    @UiField Button channelsDialogButton;
    @UiField TextBox messageToSend;
    @UiField HTML status;

    ChannelsDialog channelsDialog;

    JavaScriptObject subscription;

	final CometdClient cometdClient = 
		new PersistentSubscribersCometdClient(new CometdClientImpl());
	private boolean subscribesAdded = false;
	
    public CometdPanel() {
    	initWidget(uiBinder.createAndBindUi(this));
    	cometdClient.addConnectionListener(new CometConnectionListener() {
			@Override
			public void onConnected() {
				Log.debug("#### Connected ####");
				addSubscribers();
			}

			@Override
			public void onDisconnected() {
				Log.debug("#### Disconnected ####");
			}
		});
		cometdClient.addScriptLoadListener(new ScriptLoadListener() {
			@Override
			public void onLoad() {
				cometdClient.addListener("/meta/*", new JsoListener<CometdJso>() {
					@Override
					public void onMessageReceived(CometdJso metaMessage) {
						CometdMetaMessage message = 
							JSONToDomain.getCometdMetaMessage(new JSONObject(metaMessage)); 
						logCometdActivity (message, metaMessage);
					}
				});
			}
		});
		unsubscribe.addClickHandler(new ClickHandler(){ 
        	public void onClick(ClickEvent event) {
        		Boolean result = new Boolean (Window.confirm("Todo OK?"));
        		Log.debug(Window.getTitle() + result.toString());
        		Log.debug("ClientHeight: " + Window.getClientHeight());
        		Log.debug("ClientWidth: " + Window.getClientWidth());
        	}});
		//ConnectionConfig connectionConfig = new ConnectionConfig(ServerPaths.COMETD_SERVICE);
		//connectionConfig.requestHeaderName = "userId";
		//connectionConfig.requestHeaderValue = "" + ((int) (Math.random() * 1000));
		//cometdClient.connect(connectionConfig);
        //channelsDialog = new ChannelsDialog();
    }
    
    public void setStatusMessage (String message) {
    	status.setHTML(message);
    }

    @UiHandler("disconnect")
    void handleDisconnect(ClickEvent e) {
        cometdClient.disconnectAsync();
    }

    @UiHandler("unsubscribe")
    void handleUnsubscribe(ClickEvent e) {
        cometdClient.unsubscribe(subscription);
    }

    @UiHandler("publishMessageToChannelHello")
    void handleSendMessageToChannelHello(ClickEvent e) {
		cometdClient.publish(ChannelOf.ALERTS, messageToSend.getText());
    }
    
	private void addSubscribers() {
		if (!subscribesAdded) {
			subscribesAdded = true;
			Log.debug("Adding subscriber to: " + ChannelOf.ALERTS);
			subscription = cometdClient.addSubscriber(ChannelOf.ALERTS,
				new JsoListener<CometdJso>() {
                        @Override
                        public void onMessageReceived(CometdJso metaMessage) {
                            CometdMetaMessage message =
                                    JSONToDomain.getCometdMetaMessage(new JSONObject(metaMessage));
                            Log.debug("@@@@@@MENSAJE RECIBIDO!!! - Canal: " + ChannelOf.ALERTS + "-- message: " + new JSONObject(metaMessage));
                        }
                    }, new JsoListener<Subscription>() {
					@Override
					public void onMessageReceived(Subscription subscription) {
						Log.debug("@@ Subscription: " + subscription._toString());
					}
				});

                                        /*
        cometdClient.addScriptLoadListener(new ScriptLoadListener() {
                @Override
                public void onLoad() {
                         cometdClient.addListener(ChannelOf.HELLO, new JsoListener<CometdJso>() {
                                @Override
                                public void onMessageReceived(CometdJso metaMessage) {
                                        CometdMetaMessage message =
                                                JSONToDomain.getCometdMetaMessage(new JSONObject(metaMessage));
                                        Log.debug("MENSAJE RECIBIDO!!! - Canal: " + ChannelOf.HELLO + "-- message: " + new JSONObject(metaMessage));
                                }
                        });

                }

        });*/

 
//			new Timer() {
//				@Override
//				public void run() {
//					cometdClient.unsubscribe(subscription);
//					cometdClient.disconnect();
//				}
//			}.schedule(5000);
		}
	}
	
	private String channel;

	private void logCometdActivity (CometdMetaMessage message, CometdJso metaMessage) {
		if (channel != null && channel.equals(message.channel)) return;
		channel = message.channel;
		//Log.debug(" CometdMetaMessage: " + message._toString());
		Log.debug(" metaMessage: " + new JSONObject(metaMessage));
	}


        UploadDocumentDialog uploadFileDialog;

    @UiHandler("channelsDialogButton")
    void onClick(ClickEvent e) {
        uploadFileDialog = new UploadDocumentDialog();
        uploadFileDialog.show();
        //channelsDialog.show(this.getAbsoluteLeft() + 100, this.getAbsoluteTop() + 100);
    }
	
}